<?php

namespace app\admin\event;

use app\admin\model\KnscyGoodRelateTicket;

class GoodRelateTicketEvent
{
    public function handle($event)
    {
        //监听文章与门票关联
        list(  $entry_id, $self_ids) = $event;
        if (empty($entry_id)) {
            return false;
        }
        $relateOrm = new KnscyGoodRelateTicket();
        if ($self_ids) {
            $arrCategoryIds = array_unique(array_filter(explode(',', $self_ids)));
            $arrCategoryIds = array_map(function ($category_id) {
                return trim($category_id);
            }, $arrCategoryIds);
        } else {
            $arrCategoryIds = [];
        }
        //主体已存在的分类
        $arrExitsCategoryIds = $relateOrm->where(['good_id' => $entry_id])->column('ticket_id');
        if ($arrExitsCategoryIds) {
            $arrExitsCategoryIds = array_values($arrExitsCategoryIds);
            #删除的分类
            $arrDelCategoryIds = array_diff($arrExitsCategoryIds, $arrCategoryIds);
            #新增的分类
            $arrInsertCategoryIds = array_diff($arrCategoryIds, $arrExitsCategoryIds);
        } else {
            $arrDelCategoryIds = [];
            $arrInsertCategoryIds = $arrCategoryIds;
        }
        //删除分类联系
        if ($arrDelCategoryIds) {
            $relateOrm->where(['good_id' => $entry_id])->whereIn('ticket_id', $arrDelCategoryIds)->delete();
        }
        //新增分类
        if ($arrInsertCategoryIds) {
            $arrInsertCategoryIdsData = array_map(function ($self_id) use ($entry_id) {
                return [ 'good_id' => $entry_id, 'ticket_id' => $self_id];
            }, $arrInsertCategoryIds);
            $relateOrm->saveAll($arrInsertCategoryIdsData);
        }
    }

}